package com.cunjin.menu.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cunjin.menu.dao.MenuDao;
import com.cunjin.menu.dto.MenuDTO;
import com.cunjin.menu.entity.MenuEntity;
import com.cunjin.menu.service.MenuService;


@Service
public class MenuServiceImpl  implements MenuService {
	
	@Autowired
	private MenuDao dao;
	
	@Transactional(readOnly=false)
	@Override
	public List<MenuDTO> initTree(Integer fatherId) {
		
		List<MenuDTO> list=new ArrayList<MenuDTO>();
		
		//前台传入参数
		if(null ==fatherId){
			MenuEntity menuEntity = dao.findRoot();
			
			//拿到fatherid
			Integer rootId = menuEntity.getId();
			//根据fatherid判断是否还有子节点
			int checkLeafcount = dao.checkLeaf(rootId);
			
			//checkLeafcount大于0说明有子节点
			
			MenuDTO menudto=new MenuDTO();
			menudto.setId(menuEntity.getId());
			menudto.setText(menuEntity.getMenuName());
			if(checkLeafcount>0){
				menudto.setState("closed");
			}
			list.add(menudto);
		}else{
			List<MenuEntity> menuEntity = dao.findChildrenByFatherId(fatherId);
			for (MenuEntity menu : menuEntity) {
				
				//将所有数据封装在数据传输层
				Map<String,Object> attributes=new HashMap<String,Object>();
				MenuDTO menudto=new MenuDTO();
				int checkLeafid = dao.checkLeaf(menu.getId());
				
				menudto.setId(menu.getId());
				menudto.setText(menu.getMenuName());
				attributes.put("url",menu.getUrl());
				menudto.setAttributes(attributes);
				
				if(checkLeafid>0){
					menudto.setState("closed");
				}
				list.add(menudto);
			}
		}
		return list;
	}

}
